package com.example.shareapp.ui;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;

import android.R.bool;
import android.os.StrictMode;
import android.util.Log;

public class ExistsChecker {
	private ArrayList<String> _pnames;
	private HashMap<String, Number> _map;
	
	public ExistsChecker(ArrayList pnames) {
		this._pnames = pnames;
	}
	
	public static String getMD5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(input.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			String hashtext = number.toString(16);
			// Now we need to zero pad it if you actually want the full 32 chars.
			while (hashtext.length() < 32) {
				hashtext = "0" + hashtext;
			}
			return hashtext;
		}
		catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String getMda(String input){
		return ExistsChecker.getMD5(input).substring(0, 10);
	}
	
	private String appListToStr(ArrayList<String> pnames) {
		String str = "";
		for (int i = 0; i < pnames.size(); i++) {
			String pname = pnames.get(i);
			if(str != ""){
				str = str + ",";
			}
			str += this.getMD5(pname).substring(0, 10);
		}

		return str;
	}
	
	public HashMap<String, Number> check(){
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads().detectDiskWrites().detectNetwork()
		.penaltyLog().build());
		HttpHelper hh = new HttpHelper();
		String url = "http://sapk.tjx.be/s.php?e=" + this.appListToStr(this._pnames);
		String retStr = hh.httpGet(url, null);
		String[] split = retStr.split(",");
		
		HashMap<String, Number> map = new HashMap<String, Number>();
		for(int i = 0; i < this._pnames.size(); i++){
			map.put(this._pnames.get(i), Integer.parseInt(split[i]));
		}
		return map;
	}
	
	public int exists(String pname){
		int v = (Integer) this._map.get(pname);
		return v;
	}
	
}
